package com.zuoshenge.sys.config;

import com.zuoshenge.sys.service.MyUserDetailService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.rememberme.JdbcTokenRepositoryImpl;
import org.springframework.security.web.authentication.rememberme.PersistentTokenRepository;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.CorsConfigurationSource;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;

import javax.annotation.Resource;
import java.util.Collections;

@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
//    @Bean
//    在spring工厂中自定义的passwordEncoder，在里面自定义密码加密的方式，如果spring工厂中没有自定义的passwordEncoder，那么默认的passwordEncoder就由DelegatingPasswordEncoder实现
//    在DelegatingPasswordEncoder中会根据密码的前缀{xxx}进行判断和选择以哪种方式进行加密
//    当自定义passwordEncoder并且明确指定了哪种加密方式,那么验证密码就不需要添加前缀,整个系统都会以确定的验证方式进行验证
//    public PasswordEncoder passwordEncoder() {
//        return new BCryptPasswordEncoder();
//    }

//    @Bean
//    public UserDetailsService userDetailsService() {
//        InMemoryUserDetailsManager inMemoryUserDetailsManager = new InMemoryUserDetailsManager();
//        123的BCryptPasswordEncoder密文为$2a$10$FcVNryaDhxDkAHdVtVRYXelDbUJNw9eFQQqwWKGDrj./YKobKaOES
//        inMemoryUserDetailsManager.createUser(User.withUsername("root").password("$2a$10$FcVNryaDhxDkAHdVtVRYXelDbUJNw9eFQQqwWKGDrj./YKobKaOES").roles("admin").build());
//        return inMemoryUserDetailsManager;
//    }

    @Resource
    private MyUserDetailService myUserDetailService;

    @Resource
    private PasswordEncoder passwordEncoder;

    @Bean
    public PasswordEncoder passwordEncoder() {
        //不使用密码加密
        //return NoOpPasswordEncoder.getInstance();
        //使用默认的BCryptPasswordEncoder加密方案
        //strength=10，即密钥的迭代次数(strength取值在4~31之间，默认为10)
        //return new BCryptPasswordEncoder(10);
        //利用工厂类PasswordEncoderFactories实现,工厂类内部采用的是委派密码编码方案.
        //return PasswordEncoderFactories.createDelegatingPasswordEncoder();
        return new BCryptPasswordEncoder();
    }

//    @Bean
//    public PersistentTokenRepository persistentTokenRepository() {
//        JdbcTokenRepositoryImpl tokenRepository = new JdbcTokenRepositoryImpl();
//        tokenRepository.setDataSource(dataSource);
//        tokenRepository.setCreateTableOnStartup(true);
//        return tokenRepository;
//    }


//    // ⾃定义 filter 交给⼯⼚管理
//    @Bean
//    public LoginFilter loginFilter() throws Exception {
//        LoginFilter loginFilter = new LoginFilter();
//        loginFilter.setFilterProcessesUrl("/doLogin");// 指定认证url
//        loginFilter.setUsernameParameter("uname");// 指定接收json ⽤户名 key
//        loginFilter.setPasswordParameter("passwd");// 指定接收 json 密码 key
//        loginFilter.setAuthenticationManager(authenticationManagerBean());
//        loginFilter.setRememberMeServices(rememberMeServices());
//        // 设置认证成功时使⽤⾃定义rememberMeService
//        // 认证成功处理
//        loginFilter.setAuthenticationSuccessHandler((req, resp, authentication) -> {
//            Map<String, Object> result = new HashMap<String, Object>();
//            result.put("msg", "登录成功");
//            result.put("⽤户信息", authentication.getPrincipal());
//            resp.setContentType("application/json;charset=UTF-8");
//            resp.setStatus(HttpStatus.OK.value());
//            String s = new
//                    ObjectMapper().writeValueAsString(result);
//            resp.getWriter().println(s);
//        });
//        // 认证失败处理
//        loginFilter.setAuthenticationFailureHandler((req, resp, ex) -> {
//            Map<String, Object> result = new HashMap<String, Object>();
//            result.put("msg", "登录失败: " + ex.getMessage());
//            resp.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value());
//            resp.setContentType("application/json;charset=UTF-8");
//            String s = new ObjectMapper().writeValueAsString(result);
//            resp.getWriter().println(s);
//        });
//        return loginFilter;
//    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(myUserDetailService).passwordEncoder(passwordEncoder);
    }


    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                // 允许所有get请求访问，不仅仅只能放行请求类型，还能放行路径类型
                .antMatchers(HttpMethod.GET).permitAll()
                .antMatchers("game/**").permitAll()
                .antMatchers("auth/**").permitAll()
                .antMatchers("user/**").permitAll()
//                .anyRequest().authenticated()
                .and()
//                .rememberMe()
//                .tokenRepository(persistentTokenRepository())
//                .tokenValiditySeconds(60 * 60 * 24)
//                .userDetailsService(myUserDetailService)
//                .and()
                .cors().configurationSource(corsConfigSource())
                .and()
                .formLogin()
                .permitAll()
                .and()
                .csrf().disable();
    }

    private CorsConfigurationSource corsConfigSource() {
        CorsConfiguration configuration = new CorsConfiguration();
        configuration.setAllowedHeaders(Collections.singletonList("*"));
        configuration.setAllowedOrigins(Collections.singletonList("*"));
        configuration.setAllowedMethods(Collections.singletonList("*"));
        configuration.setMaxAge(3600L);
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", configuration);
        return source;
    }
}
